
var SUCCESS = "SUCCESS";
var ERROR = "ERROR";
var KeyWord_LoginOut = "登录过期";
function myAjaxGet(url,succFunc,compFunc,errFunc){
	  $.jBox.tip("数据交互中...", 'loading');
	  url = encodeURI(encodeURI(url));
	  $.ajax({
			dataType : 'html',
			url : url,
			type : 'get',
			cache: false, 
			contentType: "application/x-www-form-urlencoded;charset=UTF-8",  
			success : function(result) {
				if(typeof(succFunc) != 'undefined' && succFunc != null && succFunc !=''){
					if(result == ""){
						result = '{resultCode:"ERROR",value:"系统没有返回结果."}';
					}
					if(result.indexOf(KeyWord_LoginOut) != -1){
						succFunc({'resultCode':'LOGIN_OUT','value':'登录过期:请尝试刷新页面，或重新登录。'});
					}else{
						var data = eval('(' + result.substr(0,result.lastIndexOf('}')+1) + ')');
						succFunc(data);
					}
				}
			},
			error : function(result, status) {
				if(typeof(errFunc) != 'undefined' && errFunc != null && errFunc !='')
					errFunc(result,status);
			},
			complete : function() {
				if(typeof(compFunc) != 'undefined' && compFunc != null && compFunc !=''){
					compFunc();
					return;
				}
				window.setTimeout(function () { $.jBox.closeTip(); }, 1500);
			}
		});
}



function myAjaxGet_NoTip(url,succFunc,compFunc,errFunc){
	  url = encodeURI(encodeURI(url));
	  $.ajax({
			dataType : 'html',
			url : url,
			type : 'get',
			cache: false, 
			contentType: "application/x-www-form-urlencoded;charset=UTF-8",  
			success : function(result) {
				if(typeof(succFunc) != 'undefined' && succFunc != null && succFunc !=''){
					if(result == ""){
						result = '{resultCode:"ERROR",value:"系统没有返回结果."}';
					}
					if(result.indexOf(KeyWord_LoginOut) != -1){
						succFunc({'resultCode':'LOGIN_OUT','value':'登录过期:请尝试刷新页面，或重新登录。'});
					}else{
						//var data = eval('(' + result + ')');
						var data = eval('(' + result.substr(0,result.lastIndexOf('}')+1) + ')');
						succFunc(data);
					}
				}
			},
			error : function(result, status) {
				if(typeof(errFunc) != 'undefined' && errFunc != null && errFunc !='')
					errFunc(result,status);
			},
			complete : function() {
				if(typeof(compFunc) != 'undefined' && compFunc != null && compFunc !=''){
					compFunc();
					return;
				}
			}
		});
	
}

function myAjaxPost_NoTip(url,data,succFunc,compFunc,errFunc){
	  url = encodeURI(encodeURI(url));
	  $.ajax({
			dataType : 'html',
			url : url,
			type : 'post',
			data: data,
			cache: false, 
			contentType: "application/x-www-form-urlencoded;charset=UTF-8",  
			success : function(result) {
				if(typeof(succFunc) != 'undefined' && succFunc != null && succFunc !=''){
					if(result == ""){
						result = '{resultCode:"ERROR",value:"系统没有返回结果."}';
					}
					if(result.indexOf(KeyWord_LoginOut) != -1){
						succFunc({'resultCode':'LOGIN_OUT','value':'登录过期:请尝试刷新页面，或重新登录。'});
					}else{
						var data = eval('(' + result + ')');
						succFunc(data);
					}
				}
			},
			error : function(result, status) {
				if(typeof(errFunc) != 'undefined' && errFunc != null && errFunc !='')
					errFunc(result,status);
			},
			complete : function() {
				if(typeof(compFunc) != 'undefined' && compFunc != null && compFunc !=''){
					compFunc();
					return;
				}
			}
		});
	
}



function stringToXml(xmlString) {
    // for IE
    if (window.ActiveXObject) {
      var xmlobject = new ActiveXObject("Microsoft.XMLDOM");
      xmlobject.async = "false";
      xmlobject.loadXML(xmlString);
      return xmlobject;
    }
    // for other browsers
    else {
      var parser = new DOMParser();
      var xmlobject = parser.parseFromString(xmlString, "text/xml");
      return xmlobject;
    }
  }
// convert xml object to string
function xmlToString(xmlObject) {
    // for IE
    if (window.ActiveXObject) {       
      return xmlObject.xml;
    }
    // for other browsers
    else {        
      return (new XMLSerializer()).serializeToString(xmlObject);
    }
  }

function jsonToString(obj) {
	var THIS = this;
	switch (typeof (obj)) {
	case 'string':
		return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
	case 'array':
		return '[' + obj.map(THIS.jsonToString).join(',') + ']';
	case 'object':
		if (obj instanceof Array) {
			var strArr = [];
			var len = obj.length;
			for ( var i = 0; i < len; i++) {
				strArr.push(THIS.jsonToString(obj[i]));
			}
			return '[' + strArr.join(',') + ']';
		} else if (obj == null) {
			return 'null';

		} else {
			var string = [];
			for ( var property in obj)
				string.push(THIS.jsonToString(property) + ':'
						+ THIS.jsonToString(obj[property]));
			return '{' + string.join(',') + '}';
		}
	case 'number':
		return obj;
	case false:
		return obj;
	}
}

function stringToJson(obj) {
	return eval('(' + obj + ')')
	//return eval_r('(' + obj + ')');
}


/**
 * 取得所有checkbox选中的值
 * 
 * @param name
 *            checkbox的name属性
 * @param func
 *            针对每个选中的checkbox值的执行方法
 * @returns 选中的checkbox的值 1，2，3，4
 */
function getCheckedCheckbox(name,func){
	var vals = "";
	$("input[name='"+name+"']:checkbox:checked").each(function(){ 
		vals= vals + $(this).val()+","; 
		if(typeof(func) != "undefined") func($(this).val());
	}); 
	if(vals.length > 0)vals = vals.substring(0, vals.length - 1); // 最后一个逗号去除
	return vals;
	
}

function mainCheckBoxClick(mainCheckBoxId,childrenCheckBoxName){
	if($("#" + mainCheckBoxId).attr("checked")){
		checkedAllCheckbox(childrenCheckBoxName);
	}else{
		unCheckAllCheckbox(childrenCheckBoxName);
	}
}

function checkedAllCheckbox(name){
	$("input[name='"+name+"']").attr("checked","true"); 
}

function unCheckAllCheckbox(name){
	$("input[name='"+name+"']").removeAttr("checked"); 
}

function hideColumn(tableId,columnIndex){
	 $("#"+tableId+" tr th:nth-child("+columnIndex+")").hide();
	 $("#"+tableId+" tr td:nth-child("+columnIndex+")").hide();
}

function showColumn(tableId,columnIndex){
	 $("#"+tableId+" tr th:nth-child("+columnIndex+")").show();
	 $("#"+tableId+" tr td:nth-child("+columnIndex+")").show();
}


// 1.商业价值 2.NBA--->
function formatIdNamestrToEasyInfo(idNames){
	if(idNames == "" || idNames == "undefined")
		 return new Array();
	var id_NameArray = new Array();
	id_NameArray = idNames.split(" ");
	var objArray = new Array();
	var idArray = new Array();
	var nameArray = new Array();
	for (var i=0, l=id_NameArray.length; i < l; i++) {
		if( $.trim(id_NameArray[i]) == "")
			continue;
		try{
			var obj = new Object();
			var tmp = id_NameArray[i].split(".");
			idArray[idArray.length] = $.trim(tmp[0]);
			nameArray[nameArray.length] = $.trim(tmp[1]);
			obj.id =  $.trim(tmp[0]);
			obj.name =  $.trim(tmp[1]);
			objArray[objArray.length] = obj;
		}catch(err){
			continue;
		}
	}
	var result = new Object();
	result.idNameArray = objArray;
	result.idArray = idArray;
	result.nameArray = nameArray;
	result.size = objArray.length;
	return result;
}




function InputKeyUpClearChar(inputId,chars){
	var value = $("#"+inputId).val();
	if(value == "" || chars=="" || typeof(chars) == "undefined"){
		return;
	}
	var charArr = chars.split("&");
	for(x in charArr){
		while(value.indexOf(charArr[x]) != -1){
			value = value.replace(charArr[x],"");
		}
	}
	$("#"+inputId).val(value)
}

//easyUi日期控件中文与样式变化
function easyUiDateBoxSet(){
if($.fn.calendar){
	 $.fn.calendar.defaults.weeks = ['日','一','二','三','四','五','六'];
	 $.fn.calendar.defaults.months = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];
	 $.fn.datebox.defaults.formatter = function(date){
	        var y = date.getFullYear();
	        var m = date.getMonth()+1;
	        var d = date.getDate();
	        return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
	 };
    $.fn.datebox.defaults.parser = function(s){
        if (!s) return new Date();
        var ss = s.split('-');
        var y = parseInt(ss[0],10);
        var m = parseInt(ss[1],10);
        var d = parseInt(ss[2],10);
        if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
            return new Date(y,m-1,d);
        } else {
            return new Date();
        }
    };
}
}

function isNull(str){
	if(str == '' || str == null || (str+'') == 'undefined'){
		return true;
	}
	return false;
}

/**url:a=1&b=2 name:a return 1;*/
function getUrlParam(url,name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = url.match(reg);
    if (r != null) return unescape(r[2]); return null;
}

function getCurrentTime(){
	var date = new Date(); // 日期对象
	var now = "";
	now = date.getFullYear()+"-"; // 读英文就行了
	var month = (date.getMonth()+1); if(month < 10) month = "0" + month;
	var day = date.getDate(); if(day < 10) day = "0" + day;
	var hour = date.getHours(); if(hour < 10) hour = "0" + hour;
	var minute = date.getMinutes(); if(minute < 10) minute = "0" + minute;
	var second = date.getSeconds(); if(second < 10) second = "0" + second;
	now = now + month+"-";// 取月的时候取的是当前月-1如果想取当前月+1就可以了
	now = now + day+" ";
	now = now + hour+":";
	now = now + minute+":";
	now = now + second+"";
	return now;
}

function doDateFormatter(dateTime,len){
	if(dateTime == '' || dateTime == null || (dateTime + '') == 'undefined')
		return '';
	else
		return (dateTime + '').substring(0,len);
}

//1000000--> 1,000,000
function convertToMoney(str) 
{ 
	var pp=0; 
	if(str.indexOf( ", ")> 0) 
	pp=str.indexOf( ", ") 
	else if(str.indexOf( ". ")> 0) 
	pp=str.indexOf( ". ") 
	else 
	pp=str.length-1; 
	pp=pp-3; 
	if(pp <=0)return; 
	var s=str.substring(0,pp); 
	var e=str.substring(pp+1); 
	var str1=s+ ", "+e; 
	convertToMoney(str1); 
}

// 格式化金额  
function formatMoney($cell) {  
    var reg = /[\$,%]/g;  
    var key = parseFloat( String($cell).replace(reg, '')).toFixed(2); // toFixed小数点后两位  
    return isNaN(key) ? 0.00 : key;  
};


function formatCurrency(num) {
	if(isNull(num)) return "";
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-')  + num + '.' + cents);
}

/** 还原货币格式化函数 **/
function restoreFormatCurrency(num){
   	var num1=num.replace(',','').replace(/,/g,''); 
    return num1;
}

//产品价格单位转汉
function convertToChineseTimeUnit(priceUnit){
	if(priceUnit=='Year') priceUnit = "年"
	if(priceUnit=='Month') priceUnit = "月";
	if(priceUnit=='Day') priceUnit = "天";
	if(priceUnit=='Forever') priceUnit = "永久";
	return priceUnit;
}

//业务企业状态转汉
function convertToBusinessStatus(value){
	if(value == -1){ return "<label>未下过订单</label>";}
	else if(value == 0){ return "<label>订单未支付</label>";}
	else if(value == 1){ return "<label style='color:red;'>已支付未开通</label>";}
	else if(value == 2){ return "<label style='color:green;'>已开通上架</label>";}
	else if(value == 3){ return "<label style='color:red;'>过期未下架</label>";}
	else if(value == 4){ return "<label style='color:gray;'>过期已下架</label>";}
	else{
		return "<label>未知状态</label>";
	}
}


function getWebRootPath() {// 得到cms
    var webroot=document.location.href;
    var httpWay = webroot.substring(0,webroot.indexOf('//'));;
    webroot=webroot.substring(webroot.indexOf('//')+2,webroot.length);
    var domain=webroot.substring(0,webroot.indexOf('/'));
    webroot=webroot.substring(webroot.indexOf('/')+1,webroot.length);
    project=webroot.substring(0,webroot.indexOf('/'));
    var rootpath=httpWay+"//"+domain+"/"+project;
    return rootpath;
}

//表格中标题的显示字数，非汉字字符时只算显示半位
function titleShowCharNumberFormatter(title,showNum){
	if(typeof title == "undefined" ) {
		return "";
	}
	if( typeof showNum == "undefined" || !(showNum>=0) ) {
		return title;
	}

	var myReg = /^[\u4e00-\u9fa5]+$/;//非汉字算多加一位
	var charArray = title.split("");
	var addLength = 0;
	for(x in charArray){
		if (!myReg.test(charArray[x])) {
			addLength++;
	     }
	}
	showNum = showNum + addLength/2;
	
	if(title.length > showNum){
		return title.substring(0,showNum)+"...";
	}
	return title;
}

/**
 * js日期格式化
 */
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 禁用页面backspace后退
 */
function backspace(evt){
	if(evt.keyCode==8){
		if((evt.srcElement.tagName=="INPUT" || evt.srcElement.tagName=="TEXTAREA") && evt.srcElement.readOnly==false){
			evt.returnValue = true;
		}else{
			evt.returnValue = false;
		}
	}
}